package com.xbb.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 图片上传
 * @author 关关
 *
 */
@RequestMapping("/fore")
@Controller
public class ImgController {
	
	/**
	 * 图片上传
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/imgUpload")
	public Object imgUpload(HttpServletRequest request, MultipartFile pictureFile) {
		Map<String, Object> map = new HashMap<String, Object>();
		System.out.println(pictureFile);
		try {
			String imgPath = null;// 装配后的图片地址
			// 上传图片
			if (pictureFile != null && !pictureFile.isEmpty()) {
				// 使用UUID给图片重命名，并去掉四个“-”
				String name = UUID.randomUUID().toString().replaceAll("-", "");
				// 获取文件的扩展名
				String ext = FilenameUtils.getExtension(pictureFile.getOriginalFilename());
				// 设置图片上传路径
				String url = "E:\\HBulider workspace\\springboot-crm-manage-mp\\img";
				System.out.println(url);
				File file = new File(url);
				if (!file.exists()) {
					file.mkdir();
				}
				// 以绝对路径保存重名命后的图片
				pictureFile.transferTo(new File(url + "/" + name + "." + ext));
				// 装配图片地址
				imgPath = "img/" + name + "." + ext;
			}
			System.out.println("图片路径："+imgPath);
			
			if (imgPath!=null) {
				map.put("code", "0");
				map.put("msg", "图片上传成功");
				map.put("data", "{\"src\":\""+imgPath+"\"}"); 
			} else {
				map.put("code", "1");
				map.put("msg", "图片上传失败");
			}
			return map;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return map;
	}

}
